package com.jt.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jt.mapper.MenuMapper;
import com.jt.pojo.Menu;
import com.jt.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> getMenuList() {
        List<Menu> list = this.list();
        return getTree(list);
    }

    private List<Menu> getTree(List<Menu> menuList) {
        List<Menu> oneMenu = menuList.stream().filter(a -> a.getParent().equals("0")).collect(Collectors.toList());
        setSon(menuList, oneMenu);
        return oneMenu;
    }

    private void setSon(List<Menu> menuList, List<Menu> oneMenu) {
        oneMenu.forEach(one -> {
            List<Menu> children = menuList.stream().filter(item -> item.getParent().equals(one.getId())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(children)) {
                one.setChildren(children);
                setSon(menuList, children);
            }
        });
    }
}
